<!--
 * @Author: 常安民 changanmin1@crdigital.com.cn
 * @Date: 2024-05-11 14:09:19
 * @LastEditors: 常安民 changanmin1@crdigital.com.cn
 * @LastEditTime: 2024-08-09 20:37:47
 * @FilePath: /console-web/src/views/trip/manager/runtrip/openCardDetail.vue
 * @Description: 
 * @email:anmin@foxmail.com
 * Copyright (c) 2024 by 华润数科控股有限公司/常安民, All Rights Reserved. 
-->
<template>
  <div class="detail-form" v-if="loadingFinish">
    <Form :model="formInfo" ref="formInfo" class="ivu-form-no-margin-bottom form" :rules="rule" :label-width="120">
      <Row :gutter="32" class="code-row-bg">
        <Col span="12" style="border: none" v-if="isPlatformAdmin">
          <FormItem prop="tenantCode" label="所属租户">
            <Select
              :disabled="!!formInfo.crtripAccount.crtripId || disabled"
              label-in-value
              filterable
              :value="formInfo.crtripAccount.tenantCode"
              style="width: 100%"
              clearable
              @on-change="
                ({ label = '', value = '' } = {}) => {
                  formInfo.crtripAccount.tenantCode = value.trim()
                  formInfo.crtripAccount.tenantName = label.trim()
                }
              "
            >
              <Option v-for="tenant in tenantList" :value="tenant.tenantCode" :key="tenant.id">
                {{ tenant.tenantName }}
              </Option>
            </Select>
          </FormItem>
        </Col>
        <Col span="12" style="border: none">
          <FormItem prop="crtripId" label="润出行账号ID">
            <Input
              v-model="formInfo.crtripAccount.crtripId"
              :maxlength="50"
              style="width: 100%"
              placeholder="请输入润出行账号ID"
              :disabled="disabled"
              clearable
            ></Input>
          </FormItem>
        </Col>
        <Col span="12" style="border: none">
          <FormItem prop="surName" label="姓名">
            <Input
              v-model="formInfo.crtripAccount.surName"
              :maxlength="50"
              style="width: 100%"
              placeholder="请输入姓名"
              :disabled="disabled"
              clearable
            ></Input>
          </FormItem>
        </Col>
        <Col span="12" style="border: none">
          <FormItem prop="mobile" label="手机号">
            <Input
              placeholder="请输入手机号"
              clearable
              :disabled="disabled"
              v-model.trim="formInfo.crtripAccount.mobile"
              :maxlength="50"
              style="width: 100%"
            ></Input>
          </FormItem>
        </Col>

        <Col span="12" style="border: none">
          <FormItem prop="identityType" label="证件类型">
            <!-- <Input
              placeholder="请输入证件类型"
              clearable
              :disabled="disabled"
              v-model.trim="formInfo.crtripAccount.identityType"
              :maxlength="50"
              style="width: 100%"
            ></Input> -->
            <Select
            :disabled="disabled"
              filterable
              v-model="formInfo.crtripAccount.identityType"
              style="width: 100%"
              clearable 
            >
              <Option v-for="item in IdentityTypeKV" :value="item.key" :key="item.key">
                {{ item.label }}
              </Option>
            </Select>
          </FormItem>
        </Col>
        <Col span="12" style="border: none">
          <FormItem prop="identityId" label="证件号">
            <Input
              placeholder="请输入证件号"
              clearable
              :disabled="disabled"
              v-model.trim="formInfo.crtripAccount.identityId"
              :maxlength="50"
              style="width: 100%"
            ></Input>
          </FormItem>
        </Col>
        <Col span="12" style="border: none">
          <FormItem prop="positionLevelName" label="差标职级名称">
            <Input
              placeholder="请输入差标职级名称"
              clearable
              :disabled="disabled"
              v-model.trim="formInfo.crtripAccount.positionLevelName"
              :maxlength="50"
              style="width: 100%"
            ></Input>
          </FormItem>
        </Col>
        <Col span="12" style="border: none">
          <FormItem prop="baseCity" label="Base城市">
            <Input
              placeholder="请输入Base城市"
              clearable
              :disabled="disabled"
              v-model.trim="formInfo.crtripAccount.baseCity"
              :maxlength="50"
              style="width: 100%"
            ></Input>
          </FormItem>
        </Col>
        <Col span="12" style="border: none">
          <FormItem prop="employeeType" label="员工类型">
            <Select
             :disabled="disabled"
              filterable
              v-model="formInfo.crtripAccount.employeeType"
              style="width: 100%"
              clearable 
            >
              <Option v-for="item in employeeTypeKv" :value="item.key" :key="item.key">
                {{ item.label }}
              </Option>
            </Select>
          </FormItem>
        </Col>
        <Col span="12" style="border: none">
          <FormItem prop="employeeId" label="员工号">
            <Input
              placeholder="请输入员工号"
              clearable
              :disabled="disabled"
              v-model.trim="formInfo.crtripAccount.employeeId"
              :maxlength="50"
              style="width: 100%"
            ></Input>
          </FormItem>
        </Col>
        <Col span="12" style="border: none">
          <FormItem prop="workingState" label="在职状态">
            <!-- <Input
              placeholder="请输入在职状态"
              clearable
              :disabled="disabled"
              v-model.trim="formInfo.crtripAccount.workingState"
              :maxlength="50"
              style="width: 100%"
            ></Input> -->
          
            <RadioGroup :disabled="disabled" v-model="formInfo.crtripAccount.workingState" size="small">
              <Radio :disabled="disabled" :label="'1'">
                <span>在职</span>
              </Radio>
              <Radio :disabled="disabled" :label="'0'">
                <span>离职</span>
              </Radio>
            </RadioGroup>
          </FormItem>
        </Col>
        <!-- <Col span="12" style="border: none" v-if="formInfo.id">
          <FormItem prop="enabled" :label="$t('common.status')">
            <RadioGroup v-model="formInfo.enabled" size="small">
              <Radio :label="'1'">
                <span>{{ $t('common.enable') }}</span>
              </Radio>
              <Radio :label="'0'">
                <span>{{ $t('common.disable') }}</span>
              </Radio>
            </RadioGroup>
          </FormItem>
        </Col>   -->
        <Col span="24">
            <FormItem prop="enabled" label="关联的第三方商旅账号表">
                <Table :columns="crtripThirdAccountColumns" :data="formInfo.thirdAccountList" border></Table>
            </FormItem>
            <FormItem prop="enabled" label="关联的用户成本中心表">
                <Table :columns="constCenterColumns" :data="formInfo.costcentersList" border></Table>
            </FormItem>
            
          </Col>
      </Row>
    </Form>
  </div>
</template>

<script>
import tenantAPI from '@/api/tenantApi.js'
import { apiTripAccountAdd, apiTripAccountQueryById, apiTripAccountUpdate } from '@api/trip/opencard/tripOpenCard.js'
import debounce from 'lodash/debounce'
import { mapGetters } from 'vuex'
import consta from './const.js'
export default {
  title: '润出行账号-详情',
  name: 'config-trip-open-card-detail',
  components: {},
  props: {
    crtripId: {
      type: String
    },
    userTenantCode: {
      type: String
    }, 
    tenantByName:{
      type:Object,
    },
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    return {
      loadingFinish: false,
      tenantList: [], // 租户列表
      // crtripThirdAccountData: [], // 差旅标准列表
      // constCenterData:[],// 成本中心
      formInfo: {
        // tenantCode: '', // 所属租户
        // crtripId: '', //润出行账号ID
        // // 姓名 (surName)
        // surName: '',
        // // 手机号 (Phone Number)
        // mobile: '',
        // // 证件类型 (ID Type)
        // identityType: '',
        // // 证件号 (ID Number)
        // identityId: '',
        // // 差标职级名称 (Position Title)
        // positionLevelName: '',
        // baseCity: '', // base城市
        // baseCityName: '', // base城市名称
        // // 员工类型 (Employee Type)
        // employeeType: '',
        // // 员工号 (Employee Number)
        // employeeId: '',
        // // 在职状态 (workingState)
        // workingState: '',
        // // 开通日期 (Start Date)
        // createTime: '',
        // // 更新日期 (Update Date)updateTime
        // updateTime: ''
        costcentersList:[],
        thirdAccountList:[],
        crtripAccount:   {
            "baseCity": "",
            "createTime":'' ,
            "crtripId": "",
            "employeeId": "",
            "employeeType": "",
            "id": "",
            "identityId": "",
            "identityType": "",
            "mobile": "",
            "positionLevelName": "",
            "surName": "",
            "tenantCode": "",
            "updateTime": '',
            "workingState": ""
        }
      },
      rule: {
        crtripId: [{ required: true, message: '请输入润出行账号ID', trigger: 'blur' }],
        employeeType: [{ required: true, message: '请选择员工类型', trigger: 'blur' }],
        employeeId: [{ required: true, message: '请输入员工号', trigger: 'blur' }],
        surName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],  
      },
      actions: [
        {
          /**
              text: "按钮label",
              theme: "warning",
              icon: "plus-round",
              action: "actionName1", //可以通过 SetActionsState  actionName1 的 state 来设置这个按钮是否 loading
          */
          text: this.$t('common.save'),
          theme: 'primary',
          action: 'save',
          handle: this.handleSave ,
          loading: false
        },
        {
          text: this.$t('common.close'),
          action: 'close',
          handle: () => {
            this.$emit('Close')
          }
        }
      ],
      crtripThirdAccountColumns: [
        {
          title: '所属租户',
          key: 'tenantCode',
          align: 'center',
          resizable: true,
          sortable: 'custom',
          render: (h, params) => {
            let title = this.tenantByName[params.row['tenantCode']] + `(${params.row['tenantCode']})`
            return h(
              'div',
              {
                attrs: {
                  class: 'ivu-table-cell ivu-table-cell-ellipsis',
                  title: title
                }
              },
              title
            )
          }
        },
        {
          title: '开卡类型',
          key: 'openCardType',
          width: 180,
          resizable: true,
          sortable: 'custom',
          render: (h, params) => {
            let title = params.row['openCardType']
            return this.renderCell(h, title)
          }
        },
        {
          title: '润出行账号ID',
          key: 'crtripId',
          width: 180,
          resizable: true,
          sortable: 'custom',
          render: (h, params) => {
            let title = params.row['crtripId']
            return this.renderCell(h, title)
          }
        },
        {
          title: '账号状态',
          key: 'accountStatus',
          width: 180,
          resizable: true,
          sortable: 'custom',
          render: (h, params) => {
            return h(
                  'StatusButton',
                  {
                    // 修改StatusButton内容居中
                    style: {
                      'justify-content': 'center'
                    },
                    props: {
                      status: params.row.accountStatus == '1' ? '0' : '1'
                    }
                  },
                  params.row.accountStatus == '1' ? '有效' : '无效'
                )
          }
        },
        {
          title: '开通日期',
          key: 'createTime',
          width: 180,
          resizable: true,
          sortable: 'custom',
          render: (h, params) => {
            let title = params.row['createTime']
            return this.renderCell(h, title)
          }
        },
        {
          title: '更新日期',
          key: 'updateTime',
          width: 180,
          resizable: true,
          sortable: 'custom',
          render: (h, params) => {
            let title = params.row['updateTime']
            return this.renderCell(h, title)
          }
        },
        {
          title: '商旅平台主键ID',
          key: 'cardId',
          width: 180,
          resizable: true,
          sortable: 'custom',
          render: (h, params) => {
            let title = params.row['cardId']
            return this.renderCell(h, title)
          }
        }
      ], 
      constCenterColumns: [
      {
          title: '所属租户',
          key: 'tenantCode',
          align: 'center',
          resizable: true,
          sortable: 'custom',
          render: (h, params) => {
            let title = this.tenantByName[params.row['tenantCode']] + `(${params.row['tenantCode']})`
            return h(
              'div',
              {
                attrs: {
                  class: 'ivu-table-cell ivu-table-cell-ellipsis',
                  title: title
                }
              },
              title
            )
          }
        }, 
        {
          title: '润出行账号ID',
          key: 'crtripId',
          width: 180,
          resizable: true,
          sortable: 'custom',
          render: (h, params) => {
            let title = params.row['crtripId']
            return this.renderCell(h, title)
          }
        },
        {
          title: '成本中心名称',
          key: 'costCenterName',
          width: 180,
          resizable: true,
          sortable: 'custom',
          render: (h, params) => {
            let title = params.row['costCenterName']
            return this.renderCell(h, title)
          }
        },
        {
          title: '成本中心Code',
          key: 'costCenterCode',
          width: 180,
          resizable: true,
          sortable: 'custom',
          render: (h, params) => {
            let title = params.row['costCenterCode']
            return this.renderCell(h, title)
          }
        },
        {
          title: '成本中心类型Code',
          key: 'costCenterTypeCode',
          width: 180,
          resizable: true,
          sortable: 'custom',
          render: (h, params) => {
            let title = params.row['costCenterTypeCode']
            return this.renderCell(h, title)
          }
        },
        {
          title: '成本中心类型名称',
          key: 'costCenterTypeName',
          width: 180,
          resizable: true,
          sortable: 'custom',
          render: (h, params) => {
            let title = params.row['costCenterTypeName']
            return this.renderCell(h, title)
          }
        },
        {
          title: '开通日期',
          key: 'createTime',
          width: 180,
          resizable: true,
          sortable: 'custom',
          render: (h, params) => {
            let title = params.row['createTime']
            return this.renderCell(h, title)
          }
        },
        {
          title: '更新日期',
          key: 'updateTime',
          width: 180,
          resizable: true,
          sortable: 'custom',
          render: (h, params) => {
            let title = params.row['updateTime']
            return this.renderCell(h, title)
          }
        } 
      ],
    }
  },
  computed: {
    ...mapGetters(['isPlatformAdmin'])
  },
  created: function() {
    this.IdentityTypeKV = []
    this.tenantList = [];
    this.employeeTypeKv = [];
    this.$Spin.show({
      render: h => {
        return h('div', [
          h('Icon', {
            class: 'spin-icon-load',
            props: {
              type: 'ios-loading',
              size: 18
            }
          }),
          h('div', '加载中...')
        ])
      }
    })
    //#region  sidelipPage 配置
    if (this.crtripId) {
      if(this.disabled){ 
          this.$emit('SetTitle', '查看润出行账号')
         this.rule = {}
        this.$emit('SetPageActions', this.actions.filter(item=>item.action=='close'))
      }else{ 
        this.$emit('SetTitle', '编辑润出行账号')
        this.$emit('SetPageActions', this.actions )
      }
    } else {
      this.$emit('SetTitle', '新增润出行账号')
        this.$emit('SetPageActions', this.actions )
    }
    this.$emit('SetPageWidth', 700)
    //#endregion
    this.init()
  },
  mounted: function() {
    this.IdentityTypeKV = consta.IdentityTypeKV;

    this.employeeTypeKv = consta.employeeTypeKv;
  },
  methods: { 
    renderCell(h, title) {
      return h(
        'div',
        {
          attrs: {
            class: 'ivu-table-cell ivu-table-cell-ellipsis',
            title: title
          }
        },
        title
      )
    },
    init() {
      if (this.crtripId) {
         // 查询详情数据
         apiTripAccountQueryById({crtripId:this.crtripId,userTenantCode:this.userTenantCode}).then(res => {
            console.log('res :>> ', res);
            this.formInfo = Object.assign({}, res.data)
            this.loadingFinish = true;  
            this.$Spin.hide(); 
          }).catch(error => {
              console.error('Error fetching trip account details:', error);
              this.$message.error('获取详情数据失败');
              this.loadingFinish = true;
              this.$Spin.hide();
            });
      }else{ 
        this.loadingFinish = true
        this.$Spin.hide()
      }
      if (this.isPlatformAdmin) {
        tenantAPI.queryTenantList().then(data => {
          this.tenantList = data;
          if (!this.formInfo.tenantCode) {
              this.$set(this.formInfo, 'tenantCode', '');
            }
            if (!this.rule.tenantCode) { 
              !this.disabled && this.$set(this.rule, 'tenantCode', [{ required: true, message: '请选择所属租户', trigger: 'blur' }]);
            }  
          }).catch(error => {
            console.error('Error fetching tenant list:', error);
            this.$message.error('获取租户列表失败');
          });
      }
    },
    handleSave:debounce(function(){
      this.$refs['formInfo'].validate(valid => {
        if (valid) {
          this.actions[0].loading = true
          if (this.formInfo.id) {
            let param = this.formInfo
            apiTripAccountUpdate(param)
              .then(data => {
                console.log('保存失败 :>> ', data)
                this.actions[0].loading = false
                if (data.code === '0') {
                  this.$message.success({
                    content: '保存成功',
                    duration: 3
                  })
                  this.$emit('Close', true)
                } else {
                  this.$message.error({
                    content: data.message || '保存失败',
                    duration: 3
                  })
                }
              })
              .catch(data => {
                this.actions[0].loading = false
              })
          } else {
            let param = this.formInfo
            apiTripAccountAdd(param)
              .then(data => {
                this.actions[0].loading = false
                if (data.code === '0') {
                  this.$message.success({
                    content: '保存成功',
                    duration: 3
                  })
                  this.$emit('Close', true)
                } else {
                  this.$message.error({
                    content: data.message || '保存失败',
                    duration: 3
                  })
                }
              })
              .catch(data => {
                this.actions[0].loading = false
              })
          }
        }
      })
    },300)
  }
}
</script>
<style scoped lang="less">
.detail-form {
  background: #f4f6fd;
  .form {
    background: #fff;
    padding: 24px 24px 12px 24px;
    .ivu-row {
      margin-bottom: 0px;
      .last-item {
        margin-bottom: 0px;
      }
    }
    .form-title {
      display: block;
      font-size: 16px;
      color: #333333;
      letter-spacing: 0;
      font-weight: 600;
    }
  }
}
</style>
